import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import api from '@/api'

export interface User {
  id: number
  username: string
  email: string
  fullName?: string
  phone?: string
  isActive: boolean
  createdAt: string
  roles: Role[]
}

export interface Role {
  id: number
  name: string
  description?: string
  isActive: boolean
  createdAt: string
}

export interface LoginRequest {
  username: string
  password: string
}

export interface LoginResponse {
  token: string
  user: User
  permissions: string[]
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const permissions = ref<string[]>([])

  const isAuthenticated = computed(() => !!token.value)

  const login = async (credentials: LoginRequest): Promise<boolean> => {
    try {
      const response = await api.post<LoginResponse>('/api/auth/login', credentials)
      const { token: authToken, user: userData, permissions: userPermissions } = response.data
      
      token.value = authToken
      user.value = userData
      permissions.value = userPermissions
      
      localStorage.setItem('token', authToken)
      axios.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    }
  }

  const logout = () => {
    token.value = null
    user.value = null
    permissions.value = []
    
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
  }

  const checkAuth = () => {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      token.value = storedToken
      axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
      // You might want to validate the token with the server here
    }
  }

  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission)
  }

  const hasRole = (roleName: string): boolean => {
    return user.value?.roles.some(role => role.name === roleName) || false
  }

  return {
    token,
    user,
    permissions,
    isAuthenticated,
    login,
    logout,
    checkAuth,
    hasPermission,
    hasRole
  }
})
